//
//  ITMath.swift
//  ITNetLibrary
//
//  Created by ellzu gu on 2021/6/1.
//

import Foundation

public class ITMath {
    
    /// 算术平均数
    /// - Parameter numbers: 数组
    /// - Returns: 平均数
    public static func average<T>(_ numbers: [T]) -> T where T: FloatingPoint {
        guard numbers.count > 0 else {
            return T(0)
        }
        var average: T = T(0)
        numbers.forEach { (t: T) in
            average = average + t
        }
        average = average / T(numbers.count)
        return average
    }
    
    /// 求方差
    /// - Parameter numbers: 数组
    /// - Returns: 方差
    public static func variance<T>(_ numbers: [T]) -> T where T: BinaryFloatingPoint {
        guard numbers.count > 0 else {
            return T(0)
        }
        let average: T = self.average(numbers)
        var varianceSum: T = T(0)
        numbers.forEach { (t: T) in
            varianceSum += T(pow(Double(t - average), 2))
        }
        let variance: T = varianceSum / T(numbers.count)
        return variance
    }
    
    ///  求标准差
    /// - Parameter numbers: 数组
    /// - Returns: 标准差
    public static func standardDeviation<T>(_ numbers: [T]) -> T where T: BinaryFloatingPoint {
        guard numbers.count > 0 else {
            return T(0)
        }
        let variance: T = self.variance(numbers)
        let standardDeviation: T = T(pow(Double(variance), 0.5))
        return standardDeviation
    }
    
}
